package com.huaxin.hxmoduleworkorder.common;

import com.huaxin.hxmoduleworkorder.dto.response.InspectionReportDTO;
import com.itextpdf.text.pdf.BaseFont;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@Component
@RequiredArgsConstructor
public class PdfGenerator {

    private final TemplateEngine templateEngine;

    // 缓存字体文件路径（只拷贝一次）
    private volatile String cachedFontPath;

    public byte[] generatePdf(InspectionReportDTO report) throws Exception {
        Context context = new Context();
        context.setVariable("report", report);
        String html = templateEngine.process("inspectionReport", context);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();

        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(
                getOrCreateFontPath(),  // ✅ 缓存路径
                "Identity-H",
                true
        );

        renderer.setDocumentFromString(html);
        renderer.layout();
        renderer.createPDF(os);
        return os.toByteArray();
    }

    private String getOrCreateFontPath() throws IOException {
        if (cachedFontPath != null) {
            return cachedFontPath;
        }
        synchronized (this) {
            if (cachedFontPath == null) {
                Path tempFont = copyFontToTemp();
                cachedFontPath = "file:" + tempFont.toAbsolutePath().toString();
            }
        }
        return cachedFontPath;
    }

    private Path copyFontToTemp() throws IOException {
        try (InputStream is = getClass().getClassLoader()
                .getResourceAsStream("static/fonts/simsun.ttc")) {
            if (is == null) {
                throw new IOException("字体文件未找到: static/fonts/simsun.ttc");
            }

            // 使用应用目录下的 temp，避免 /tmp 权限问题
            Path workDir = Path.of(System.getProperty("user.dir"));
            Path tempDir = workDir.resolve("temp");
            Files.createDirectories(tempDir);

            Path tempFont = Files.createTempFile(tempDir, "simsun-", ".ttc");
            Files.copy(is, tempFont, StandardCopyOption.REPLACE_EXISTING);
            tempFont.toFile().deleteOnExit();

            return tempFont;
        }
    }
}